﻿/** 
 * Description:用户管理
 * Date:2011-7-18
 * Author:Along	
*/
package com.community.shopping.service.logic;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.directwebremoting.util.LogErrorHandler;

import com.community.shopping.dao.UserDao;
import com.community.shopping.domain.User;

public class UserManager {
	
	public UserDao userDao;

	/**
	 * @param uerDao the uerDao to set
	 */
	public void setUserDao(UserDao uersDao) {
		this.userDao = uersDao;
	}
	private SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * 检查用户是否注册过
	 * @param tel
	 * @return
	 */
	public boolean checkTel(String tel)
	{
		boolean flag=false;
		if(userDao.getUsersByUserName(tel)!=null)
		{
			flag=true;
		}
	
		return flag;
	}
	
	//用户登录，验证OK后同时将user绑定到session
	public boolean checkUser(String username,String password,HttpServletRequest request)
	{
		boolean flag=false;
		User user=userDao.getUsersByUserName(username);
		if(user!=null)
		{
			if(password.trim().equals(user.getPassWord()))
			{
			flag=true;
			request.getSession().setAttribute("user", user);
			}
		}
	
		return flag;	
	}
	
	//用户注册，同时将user绑定到session
	public void addUser(String username,String password,String relname,String address,HttpServletRequest request)
	{
		User user=new User();
		user.setUserName(username);
		user.setPassWord(password);
		user.setRealName(relname);
		user.setAddress(address);
		user.setScore(0);
		//增加推广链接
		String refrom=request.getParameter("regfrom");
		if(refrom!=null && !"".equals(refrom))
		{
			Integer regfrom=null;
			try
			{
				regfrom=Integer.parseInt(refrom);
			}
			catch(Exception e)
			{
		        System.out.println("推广ID不存在!");
			}
			user.setRegfrom(regfrom);
		}
		user.setCreateDate(format.format(new Date()));
		user.setRegMoney(0);
		user.setLastMoney(0);
		userDao.save(user);		
		request.getSession().setAttribute("user", user);	
	}
	
	public User getUserById(String id)
	{
		User user=userDao.getUsersByID(id);
		return user;		
	}
	
	public List<User> getUserByHql(String hql,Page page)
	{
		List users=userDao.getUsers(hql,page);
		return users;		
	}
	
	public List<User> getUserByHql(String hql)
	{
		List users=userDao.getUsers(hql);
		return users;		
	}
	
	public void save(User user)
	{
		userDao.save(user);
	}
}
